package org.xx.armory.jpa;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

import static org.xx.armory.commons.Validators.rejectIfNull;

public final class PredicateBuilder {
    private List<Predicate> predicates;

    public PredicateBuilder() {
        this.predicates = new ArrayList<>();
    }

    public final PredicateBuilder add(
            Supplier<Boolean> pp,
            Predicate predicate
    ) {
        rejectIfNull(pp, "pp");
        rejectIfNull(predicate, "predicate");

        if (pp.get()) {
            this.predicates.add(predicate);
        }

        return this;
    }

    public final PredicateBuilder add(
            Predicate predicate
    ) {
        return add(() -> true, predicate);
    }

    public final Predicate build(
            CriteriaBuilder cb
    ) {
        return cb.and(this.predicates.toArray(Predicate[]::new));
    }
}
